package org.gruposp2p.openid.util;

import java.util.HashMap;
import org.apache.log4j.Logger;
import org.codehaus.groovy.grails.commons.ApplicationHolder;
import org.gruposp2p.openid.service.EmailServiceInt;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.security.access.event.AbstractAuthorizationEvent;
import org.springframework.security.authentication.event.AbstractAuthenticationEvent;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.authentication.event.InteractiveAuthenticationSuccessEvent;
import org.springframework.security.web.authentication.switchuser.AuthenticationSwitchUserEvent;

public class IdProviderApplicationListener implements ApplicationListener {

	private final Logger log = Logger.getLogger(getClass());
	
	private EmailServiceInt emailService;
	
	@Override
	public void onApplicationEvent(ApplicationEvent e) {
		log.debug("###### DNIeApplicationListener - " + e.getClass());
		if (e instanceof AbstractAuthenticationEvent) {
	         if (e instanceof InteractiveAuthenticationSuccessEvent) {
	        	 //ApplicationContext ctx = (ApplicationContext)ApplicationHolder.getApplication().getMainContext();
	        	 //emailService = (EmailServiceInt) ctx.getBean("emailService");
	        	 //HashMap<String,String> args = new HashMap<String,String>(); 
	        	 //args.put("to", "gruposp2p@gmail.com");
	        	 //args.put("from", "gruposp2p@gmail.com");
	        	 //args.put("subject", "onInteractiveAuthenticationSuccessEvent");
	        	 //args.put("view","/emails/simpleMail");
	        	 //emailService.sendEmail(args);
	        	 log.debug("DNIeApplicationListener - InteractiveAuthenticationSuccessEvent - " + e.getClass());        	 
	         }
	         else if (e instanceof AbstractAuthenticationFailureEvent) {
	        	 AbstractAuthenticationFailureEvent failureEvent = 
	        		 (AbstractAuthenticationFailureEvent)e;
	        	 log.debug("DNIeApplicationListener - AbstractAuthenticationFailureEvent - " + 
	        			 failureEvent.getException().getMessage());
	         }
	         else if (e instanceof AuthenticationSuccessEvent) {
	        	 log.debug("DNIeApplicationListener - AuthenticationSuccessEvent - " + e.getClass());
	         }
	         else if (e instanceof AuthenticationSwitchUserEvent) {
	        	 log.debug("DNIeApplicationListener - AuthenticationSwitchUserEvent - " + e.getClass());
	         }
	      } else if (e instanceof AbstractAuthorizationEvent) {
	    	  log.debug("DNIeApplicationListener - AbstractAuthorizationEvent - " + e.getClass());
	      }
	}

}
